import { ref } from 'vue'
import { defineStore } from 'pinia'
import {type RouteItem } from '@/router/setRouter';
import { ElNotification } from 'element-plus'
import setting from '@/setting'
export const useTagsViewStore = defineStore('tagsView', () => {
    const tagsView = ref<Array<RouteItem>>([]);
    const activeTagsView = ref<RouteItem>();

    /**添加view*/ 
    const addTagsView = (view: RouteItem) : boolean => {
        if (tagsView.value.some(v => v.path === view.path || v.redirect == view.path || view.redirect == v.path)) 
            return true;
        if (tagsView.value.length >= setting.maxPageNumber) {
            ElNotification({
                title: '提示',
                message: '页面数量已达上限，请关闭其他页面后再打开新页面！',
                type: 'warning',
                duration: 3000,
                offset: 50,
                customClass: 'notification-warning'
            })
            return false;
        }
        
        tagsView.value.push(Object.assign({}, view, {
            title: view.meta?.title || 'no-name'
        }))
        return true
    }
    /**删除指定的view*/ 
    const deleteTagsView = (view: RouteItem) => {
        for (const [i, v] of tagsView.value.entries()) {
            if (v.path === view.path) {
                tagsView.value.splice(i, 1)
                break
            }
        }
    }

    /**关闭所有仅保留固定的*/
    const closeAllTagsView = () => {
        tagsView.value = tagsView.value.filter(v => {
            return v.meta?.affix
        })
    }

    /**关闭其他*/
    const closeOtherTagsView = (view: RouteItem) => {
        tagsView.value = tagsView.value.filter(v => {
            return v.meta?.affix || v.path === view.path
        })
    }

    /**设置当前的view*/
    const setActiveTagsView = (view: RouteItem) => {
        activeTagsView.value = view
    } 

    return { tagsView, addTagsView  , deleteTagsView , closeAllTagsView , closeOtherTagsView  , setActiveTagsView , activeTagsView }
})